package com.seventeen.monster.mq.proxy.service.impl;

import com.seventeen.monster.common.constant.DelFlagConstants;
import com.seventeen.monster.common.constant.InstanceTypeConstants;
import com.seventeen.monster.common.exception.base.BaseException;
import com.seventeen.monster.mq.proxy.domain.MqInstance;
import com.seventeen.monster.mq.proxy.domain.MqProducerProxy;
import com.seventeen.monster.mq.proxy.mapper.MqInstanceMapper;
import com.seventeen.monster.mq.proxy.mapper.MqProducerProxyMapper;
import com.seventeen.monster.mq.proxy.service.IMqProducerProxyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 消息生产代理 服务层处理
 *
 * @author seventeen
 */
@Service
public class MqProducerProxyServiceImpl implements IMqProducerProxyService {
    @Autowired
    private MqProducerProxyMapper mqProducerProxyMapper;
    @Autowired
    private MqInstanceMapper mqInstanceMapper;

    @Override
    public List<MqProducerProxy> list() {
        return mqProducerProxyMapper.list();
    }

    @Override
    public List<MqProducerProxy> queryList(MqProducerProxy mqProducerProxy) {
        return mqProducerProxyMapper.selectList(mqProducerProxy);
    }

    @Override
    public void add(MqProducerProxy mqProducerProxy) {
        if (mqProducerProxyMapper.getByProducerProxyGroup(mqProducerProxy.getProducerProxyGroup()) != null) {
            throw new BaseException("生产代理组名重复！");
        }
        MqInstance mqInstance = mqInstanceMapper.selectById(mqProducerProxy.getInstanceId());
        if (InstanceTypeConstants.V5_X.equals(mqInstance.getInstanceType()) || InstanceTypeConstants.V_ALI_CLOUD_5_X.equals(mqInstance.getInstanceType())) {
            if (StringUtils.isBlank(mqProducerProxy.getWithTopics())) {
                throw new BaseException("绑定topic不可为空！");
            }
        }
        mqProducerProxy.setVersion(Long.toString(System.currentTimeMillis()));
        mqProducerProxy.setDelFlag(DelFlagConstants.NORMAL);
        mqProducerProxyMapper.insert(mqProducerProxy);
    }

    @Override
    public void update(MqProducerProxy mqProducerProxy) {
        mqProducerProxy.setVersion(Long.toString(System.currentTimeMillis()));
        mqProducerProxyMapper.update(mqProducerProxy);
    }
}
